 <template>
  <div class='page white-stage reassignClients'>
    <top-filter
    ref="topFilter"
    :activeItem="filterActiveItem" :ismemberIsShow="false" :customPropertyIsShow="false"
    :filterOptions="filterOptions" @load-more="loadFilter" @change-filter="changeFilterValue" @item-selected="topFilterItemSelected"></top-filter>
    <search-input v-if="isShowSearch" @search-change="searchChange"></search-input>
    <div class="pagination-fixer">
      <h6 class="target-title"><template>{{ teamName }}</template></h6>
      <el-pagination class="filter-item mgl"
      ref="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[queryData.page_size]"
      :page-size="queryData.page_size"
      layout="sizes, prev, pager, next, jumper, total"
      :total="this.total">
      </el-pagination>
    </div>
    <div class="container pdt grey" :style="containerHeight">
      <div class="clients-list">
        <div class="container pdt scroll-container grey"
        ref="my_scroller"
        :style="'padding-top: 92px;  height:' + this.scrollerHeight + 'px'" @scroll="scroll">

          <div class="rela-tip-main">
            <div class="rela-result-tip top-list-counter">总计{{ total }}条记录</div>
          </div>

          <checker v-if="batchCheck" type="checkbox" v-model="checkedClients" selected-item-class="checker-item-active">
            <checker-item class="block-item" :value="toString(client.id)" v-for="(client, index) in clientList" :key="index">
              <reassign-custom-item
                      :isLinkToFollowRecord="true"
                      @on-click="onItemClick"
                      :key="index" :value="client"
                      :suser="client.user_name"
                      :custom_type="custom_type"
                      :batchCheck="batchCheck"
                      :isChenJiao="true"
                      propPosition="bodyTop"
                      :showProp="false">
                <div class="pull-left" v-if="batchCheck"  slot="checkerItem" >
                  <div class="batch-check-item">
                    <i class="selected-ico"></i>
                  </div>
                </div>
              </reassign-custom-item>
            </checker-item>
          </checker>

          <reassign-custom-item
                  v-for="(client, index) in clientList"
                  v-else :isLinkToFollowRecord="true"
                  :key="index"
                  :showProp="false"
                  :isChenJiao="true"
                  propPosition="bodyTop"
                  :value="client" :custom_type="custom_type">
          </reassign-custom-item>
          <div class="center-content-block" v-if="loading === true">
            <mt-spinner type="snake"></mt-spinner>
          </div>
        </div>
      </div>
    </div>
    <button class="fixed-bt-btn fixed-btr0-btn" v-if="!batchCheck && !show" @click="batchCheck=true">批量分配</button>
    <button class="fixed-bt-btn fixed-btr1-btn" v-if="batchCheck" @click="batchCheck=false">取消</button>
    <button class="fixed-bt-btn fixed-btr2-btn" v-if="batchCheck" @click="selectAll">全选</button>
    <button class="fixed-bt-btn fixed-btr0-btn" v-if="batchCheck" @click="distributeTrigger">分配</button>
    <crm-cover v-if="isShowCover" :hideCoverOnClick="true"></crm-cover>
    <crm-tabbar ref="tabbar" :activeItem='activeItem' v-if="activated && !isAppMode"></crm-tabbar>

    <distribute-client
    :isShow="show"
    @on-cancel="show=false"
    :deliverTeamOpts="deliverTeamOpts"
    @on-confirm="memberSelect" />

    <x-dialog v-model="this.$store.state.app.dialogShow" >
      <div class="dialog-message">
        {{ this.$store.state.app.dialogMessage }}
      </div>
      <span class="vux-close" @click="hideDialog">知道了</span>
    </x-dialog>
    <confirm v-model="showDistributeConfirm"
        title="温馨提示"
        @on-confirm="onDistributeConfirm">
      <p style="text-align:center;">你确定要分配客户给此成员吗?</p>
    </confirm>
  </div>

</template>
<script>
  // import Vue from 'vue'
  import { getCustomSource } from '../lib/client'
  import { getSourceOptions } from '../lib/options/source'
  import { getChannelOptions } from '../lib/options/channel'
  import crmTabbar from '../components/crm-tabbar'
  import crmCover from '../components/crm-cover'
  import topFilter from '../components/top-filter'
  import teamMemberItem from '../components/team-member-item'
  import clientseasItem from '../components/clientseas-item'
  import DistributeClient from '../components/distribute-client'
  // import Scroller from 'vue-scroller'

  // import {Popup, XDialog} from 'vux'
  // import XInput from 'vux/src/components/x-input'
  // import Group from 'vux/src/components/group'
  import Popup from 'vux/src/components/popup'
  import XDialog from 'vux/src/components/x-dialog'
  import { Checker, CheckerItem } from 'vux/src/components/checker'
  import store from '../store'
  import { mapActions, mapState } from 'vuex'

  import dropdownOption from '../components/dropdown-option';
  import SearchInput from '../components/SearchInput'
  import {loadTeamSettings, loadMemberSettings, loadFilterFunc} from '../lib/filter'
  import {showDialog, hideDialog} from '../lib/dialog'
  import Q from 'q'
  import Confirm from 'vux/src/components/confirm'
  import  { mapField } from '../lib/backend'
  import reassignCustomItem from '../components/reassign-custom-item'
  import  { Pagination } from 'element-ui'
  import 'mint-ui/lib/loadmore/style.css'
  import 'mint-ui/lib/spinner/style.css'
  import 'mint-ui/lib/infinite-scroll/style.css'
  import {Loadmore, Spinner} from 'mint-ui'

  import {
    SHOW_COVER
  } from '../store/mutation-types';
  var zepto = require('npm-zepto')


  export default {
  data () {

    let overHeight = document.body.scrollHeight+10;

    return {
      activated: true,
      total: 0,
      isMore: false,
      showDistributeConfirm: false,
      activeItem: '',
      existTeamsIDs: [],
      containerHeight : 'height:'+overHeight+'px;',
      page_size : 15,
      page_index: 1,
      team_page_index: 1,
      custom_type:0,
      scrollerHeight: '',
      is_member:'',
      isShowSearch: false,
      show: false,
      filterActiveItem: {},
      loading: false,
      hasMoreData: true,
      keyword: '',
      noDataText:'',
      checkedClients: '',
      batchCheck: false,
      deliverTeamOpts: [],
      tnoDataText:'',
      init: false,
      cleanClientList : {},
      originNoDataText:'暂无数据',
      clientList:[] ,
      teamFilterOptions:[],
      teamsMembers:[],
      selectedClientId: null,
      filterData:{},
      filterOptions: [],
      currentPage: 1,
      queryData: {
        page_index: 1,
        page_size: 20
      },
      teamName: '',
      homeTop: 0
    }
  },

  components: {
    crmTabbar,
    crmCover,
    topFilter,
    clientseasItem,
    Popup,
    teamMemberItem,
    // Scroller,
    SearchInput,
    Checker,
    CheckerItem,
    XDialog,
    Confirm,
    DistributeClient,
    reassignCustomItem,
    [Pagination.name]: Pagination,
    [Loadmore.name]: Loadmore,
    [Spinner.name]: Spinner
  },



  watch: {
    clientList () {
      this.cleanClientList = {}
      this.clientList.forEach((elem, index) => {
        this.cleanClientList[elem.id] = elem
      })
    },
    checkedClients (checkedClients) {
      console.debug('checkedClients', JSON.stringify(checkedClients))
      this.selectedClientId = checkedClients
    },
    batchCheck (val) {
      if (val === false) {
        this.checkedClients = []
      }
    },
    show (val) {
      if (val === false) {
        this.selectedClientId = ''
      }
    },
    init (value) {
      if (value === true) {
        this.$nextTick(() => {
          console.log('3333')
          this.getCustoms()
        })
      }
    }
  },
  activated () {
    if (this.position) {
      this.$refs.my_scroller.scrollTop = this.position.top
    }
    let scroller = this.$refs.my_scroller

    zepto(scroller).unbind('scroll.' + this.custom_type)
      .on('scroll.' + this.custom_type, () => {
        let scrollTop = this.$refs.my_scroller.scrollTop
        this.position = {top: scrollTop}
      })
    this.activated = true
   },
   deactivated () {
     this.activated = false
     this.position = {
       // left: 200,
       top: this.homeTop
     }
   },
  methods: {
    scroll(event) {
      this.homeTop = event.target.scrollTop
      console.log('scroll', event.target.scrollTop)
    },
    caculateScroller () {
      const winHeight = window.innerHeight
      const filterHeight = this.$refs['topFilter'].$el.offsetHeight
      const tabbarHeight = this.$refs['tabbar'].$el.offsetHeight
      this.scrollerTop = filterHeight
      this.scrollerHeight = winHeight - filterHeight - tabbarHeight - 80
    },
    distributeTrigger () {
      this.initDistributeTeamOpts()
      this.show = true
    },
    initDistributeTeamOpts () {
      const data = this.$refs.topFilter.getData()
      const myTeamList = this.loginUser.my_team_list
      let deliverTeamOpts = []
      if (data.team_id) {
        deliverTeamOpts = [
          {
            key: data.team_id,
            value: myTeamList[data.team_id]
          }
        ]
      } else {
        for (const teamId in myTeamList) {
          deliverTeamOpts.push({
            key: teamId,
            value: myTeamList[teamId]
          })
        }
      }
      this.deliverTeamOpts = deliverTeamOpts
    },
    selectAll () {
      const list = []
      this.clientList.forEach((client, index) => {
        list.push(client.id + '')
      })
      this.checkedClients = list
    },
    initActiveItem () {
      let query = this.$route.query
      this.activeItem = query.activeItem
    },
    showConfirmDialog (member) {
      this.selectedMember = member
      this.showDistributeConfirm = true
    },
    onDistributeConfirm () {
      this.memberSelect(this.selectedMember)
    },
    toString (id) {
      return id + ""
    },
    loadTeamRelative () {
      loadTeamSettings({}, {checked: true}).then((options) => {
        if (options === false) return this.filterTeamIndex = 0
        this.filterOptions[1]['options'][2] = options[1]
      }).then(loadMemberSettings).then((options) => {
        if (false === options) return this.filterMemberIndex = 0
        this.filterOptions[1]['options'][1] = options[1]
        this.init = true
        this.filterData = this.$refs.topFilter.getData()
      }).catch(() => {
        this.init = true
      })
    },

    refresh (iscroll) {
      console.log('refresh')
      this.page_index = 1
      this.getCustoms();
    },
    handleSizeChange () {
    },
    handleCurrentChange (val) {
      this.queryData = {
        ...this.queryData,
        page_index: val
      }
      this.currentPage = val
      console.log('val', val, this.currentPage)
      this.getCustoms()
    },
    initPageFilters (pageData) {
      const totalPage = Math.ceil(pageData['total'] / this.queryData.page_size)
      const filters = []
      for (let i = 1; i <= totalPage; i++) {
        filters.push({
          value: i,
          text: i
        })
      }
      this.filters = filters
    },
    loadFilter :loadFilterFunc,
    log () {
      console.log('ee');
    },

    load (iscroll) {
      console.log('load')
      if (this.init) {
        this.getCustoms()
      }
      // Load new data
    },

    topFilterItemSelected(item, index) {
      console.log('topFilterItemSelected')

      if (typeof item.name !== 'undefined' && item.name === 'search') {
        this.isShowSearch  = !this.isShowSearch //搜索栏打开
      } else {
        this.isShowSearch = false//打开的是筛选栏
      }

      if(this.isShowSearch === false && this.keyword) {
        if(this.isShowSearch === false) {
          this.keyword = ''
          this.emptyCustoms()
          this.getCustoms()
        }
      }

    },

    isSameObj (obj1, obj2) {
      return JSON.stringify(obj1) === JSON.stringify(obj2)
    },
    initBatchCheck () {
      let that = this
      let items = [
        {
          'id': 'batchCheck', // 字符串
          'text': '批量分配'
        }
      ]
      const dd = window['dd']
      dd.biz.navigation.setMenu({
        backgroundColor: '#FFFFFF',
        textColor: '#0089cd',
        items: items,
        onSuccess: function (data) {
          // this.checkedClients
          if (that.batchCheck !== true) {
            that.batchCheck = true
          }
        },
        onFail: function (err) { }
      })
    },

    emptyCustoms () {
      this.clientList = []
      this.clientIDs = []
      this.page_index = 1
    },

    searchChange (value) {
      if (!value) return
      console.log('searchChange',value)
      if (typeof this.sid !== 'undefined') {
        clearTimeout(this.sid)
      }

      this.sid = setTimeout(() => {
        if(!this.originClientList) {
          this.originClientList = this.clientList
        }
        this.emptyCustoms()
        this.keyword = value
        this.getCustoms()
      }, 1000)
    },

    refreshMember (iscroll) {
      this.loadMembers();
      console.log('refreshMember')
      // Refresh current data
    },

    logMember () {
      console.log('logMember');
    },

    loadMember (iscroll) {
      console.log('loadMember')
      this.loadMembers();
      // Load new data
    },

    hidePopup (status) {
      showDialog('你取消了分配！');
      this.show = false;
      console.log('hidePopup')
    },

    hideDialog () {
      hideDialog()
      this.emptyCustoms()
      this.getCustoms()
    },

    test () {
      console.log('test')
    },

    onItemClick(clientID){
      // this.teamsMembers = [];
      this.loadMembers();
      this.initDistributeTeamOpts()
      this.show = true;
      this.selectedClientId = clientID;
      console.log('clientID: ', clientID);
    },

    memberSelect(member) {
      console.log('memberSelect: ', member.suid);
      if (!this.selectedClientId) {
        showDialog('您必须选择至少一个客户!')
        return
      }

      let info = {
        target_suid: member.suid,
        target_team_id: member.team_id,
        custom_id: this.selectedClientId,
        distribute_type: 'TP#',
        opt_type: 'TPT'
      };

      let that = this;
      this.$vux.loading.show({text:'loading'})

      store.dispatch('distribute', info).then((response) => {
        if(response.data.errcode === 0) {
          showDialog('您将客户分配给成员：'+member.name);
          that.show = false
          // that.$router.back();
          this.batchCheck = false
        } else {
          showDialog(response.data.errmsg)
          console.log(JSON.stringify(response.data));
        }
        this.$vux.loading.hide()
      }).catch((error) => {
        showDialog('系统出错!')
        this.$vux.loading.hide()
        console.log(error)
      });
    },

    getCustoms(data) {
      let defaultData = this.$refs.topFilter.getData()
      console.log(defaultData, 'defaultData')
      console.log(this.queryData, 'querydata')
      // let defaultData = this.filterData
      let that = this;
      let id = Math.random()
      this.id = id

      if (this.loading === true || this.hasMoreData === false) return

      defaultData['custom_type'] = this.custom_type;
//      defaultData['page_size'] = this.page_size;
//      defaultData['page_index'] = this.page_index;
      defaultData['is_member'] = this.is_member
      defaultData['order_by'] = 0;
      defaultData['type'] = 'distribute'

      if (this.keyword) defaultData['keyword'] = this.keyword

      // if (this.loginUser.is_team_manager === 1) defaultData['team_id'] = this.loginUser.teams[0].team_id

      data = Object.assign(this.queryData, defaultData, data);

      this.noDataText = '数据加载中...'
      store.dispatch('getCustoms', data).then((response) => {
        if (id !== this.id) return
        let resData = response.data
        if(resData.errcode == 0) {
          let freshData = []
          this.total = 0
          if (typeof this.clientIDs === 'undefined') this.clientIDs = []
          if (resData.results.data.length) {
            if (this.total != resData.results.total) this.initPageFilters(resData.results)
            this.total = resData.results.total
            this.teamName = resData.results.team_name
          }
          that.clientList = resData.results.data;
          that.page_index ++
          if(that.clientList.length) {
            that.noDataText = '';
          } else {
            this.noDataText = this.originNoDataText
          }
        } else {
          this.noDataText = this.originNoDataText
          console.log('系统服务异常！请联系管理员!', JSON.stringify(resData));
        }
        this.loading = false
      }).catch((error) => {
        this.noDataText = this.originNoDataText
        console.log(error)
        this.loading = false
      })
    },

    loadMembers (data) {
      return Q.Promise((resolve, error) => {
        let that = this
        let params = {
          page_index: this.team_page_index,
          page_size: this.page_size,
          is_own: 1,
          source: 'webapp'
        };

        params = Object.assign(params, data)
        store.dispatch('getTeams', params).then((response) => {

          setTimeout(() => {
            if (typeof response.data.results.teams !== 'undefined') {
              let teams = response.data.results.teams;
              that.filterUserFromTeam(teams)

              resolve(true)

            } else {
              console.log(that.teamsMembers)
            }

            this.endTeamLoading()

            that.team_page_index++;

          }, 800)

        }).catch((e) => {
          console.log(e)
          this.endTeamLoading()
        })
      })

    },
    //从接口中筛选出团队信息
    filterUserFromTeam(teams) {
      let temps = [];

      if(!this.existTeamsIDs) this.existTeamsIDs = []

      teams.forEach((team, index) => {
        let isSelfTeam = false

        // team.team_managers.forEach((member, mindex) => {
        //   if(member.suid === this.loginUser.id) {
        //     isSelfTeam  = true
        //   }
        // });

        if(team.id === this.loginUser.teams[0].team_id) isSelfTeam = true

        // if(true === isSelfTeam) {
          if (team.team_managers) {
            team.team_managers.forEach((member, mindex) => {
              let gid = member.suid+'_'+team.id
              if(this.existTeamsIDs.indexOf(gid) === -1)  {
                member.team_name = team.team_name;
                temps.push(member);
                // console.log(this.existTeamsIDs)
                this.existTeamsIDs.push(gid)
              }
            });
          }
          if (team.team_members) {
            team.team_members.forEach((member, mindex) => {
              let gid = member.suid+'_'+team.id
              if(this.existTeamsIDs.indexOf(gid) === -1)  {
                member.team_name = team.team_name;
                temps.push(member);
                // console.log(this.existTeamsIDs)
                this.existTeamsIDs.push(gid)
              }
            })
          }

        // }
      });
      this.teamsMembers = this.teamsMembers.concat(temps);
    },
    endTeamLoading() {
      let that = this
      setTimeout(() =>{
        if (that.$refs.team_scroller) {
          // that.$refs.team_scroller.finishInfinite(true);
          // that.$refs.team_scroller.finishPullToRefresh();
          if (that.teamsMembers.length > 0) {
            that.tnoDataText = ''
          }
          // setTimeout(() => {
          //   if(this.$refs.team_scroller) {
          //     this.$refs.team_scroller.resize()
          //   }
          // },200)
        }
      }, 1500)
    },

    //筛选器
    changeFilterValue(filterOptions) {
      this.emptyCustoms();
      this.getCustoms();
      this.initDistributeTeamOpts()
    },

    handlePopup(status){
      this.team_page_index = 1;
      if(status === 'show') {
        // setTimeout(() => {
        //   if(this.$refs.team_scroller) {
        //     this.$refs.team_scroller.resize()
        //   }
        // },200)
      } else {

      }
    },
    ...mapActions({
      'updateSourceFilter': 'updateSourceFilter',
      'updateChannelFilter': 'updateChannelFilter'
    })
  },
  computed: {
    ...mapState({
      isShowCover: state => state.app.isShowCover,
      defFilterOptions: state => state.app.filterOptions,
      loginUser: state => state.app.user,
      isUpdateSourceFilter: state => state.app.updateSourceFilter,
      isUpdateChannelFilter: state => state.app.updateChannelFilter,
      isAppMode: state => state.config.isAppMode
    })
  },
  beforeMount () {
    this.filterOptions = this.defFilterOptions
  },
  mounted () {
    if (this.loginUser.is_team_manager) {
      this.loadMembers().then((status) => {
        if (status === true) {
          this.initBatchCheck()
          this.team_page_index ++
          // this.batchCheck = true
        }
      })
    }

    if (!this.isUpdateSourceFilter) {
      getCustomSource(store).then((customSources) => {
        let sourceOptions = getSourceOptions(customSources)
        this.filterOptions[1].options.push(sourceOptions)
      })
      this.updateSourceFilter()
    }

    if (!this.isUpdateChannelFilter) {
      getChannelOptions().then((channelOptions) => {
        this.filterOptions[1].options.push(channelOptions)
      })
      this.updateChannelFilter()
    }

    let query = this.$route.query
    this.custom_type = query.custom_type
    this.is_member = query.is_member

    this.noDataText = this.originNoDataText
    this.tnoDataText = this.originNoDataText

    // this.filterOptions = this.gbfilterOptions;
    this.teamFilterOptions = this.gbfilterOptions

    this.loadMembers()
    this.loadTeamRelative()
    this.initActiveItem()
    this.$nextTick(() => this.caculateScroller())

    // this.getCustoms();
    // this.loadMembers();
  }


  }
</script>
<style lang="less">

  @import "../less/base";
  .target-title {
    text-align: center;
  }

  .clients-list{
    // margin-top: 20px;
    background-color: #EFEFF4;
    // padding-top: 10px;
  }

  .reassignClients {
    .pdscroll {
      background-color: #EFEFEF;
    }
    .clientseas-item .client-desc {
      margin-bottom: 0;
    }
  }


  .grey.container.pdt{
    // padding-top: 18px;
  }
</style>
